package com.tender.utils;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.Base64;
import java.util.Iterator;

/**
 * 根据图片的宽度、高度和是否需要旋转的条件来压缩图片
 */
public class ImageCompressionUtil {

    // 根据宽高和是否旋转来压缩图片
    public static void compressImage(File inputFile, File outputFile, int targetWidth, int targetHeight, boolean rotate, float quality) {
        try {
            // 读取原始图片
            BufferedImage originalImage = ImageIO.read(inputFile);

            // 如果需要旋转图片
            if (rotate) {
                originalImage = rotateImage(originalImage);
            }

            // 根据目标宽高压缩图片
            BufferedImage resizedImage = resizeImage(originalImage, targetWidth, targetHeight);

            // 获取图像写入器
            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
            ImageWriter writer = writers.next();

            // 设置输出流
            ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);
            writer.setOutput(ios);

            // 设置压缩参数
            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality); // 设置压缩质量

            // 写入压缩后的图像
            writer.write(null, new IIOImage(resizedImage, null, null), param);
            ios.close();
            writer.dispose();

            System.out.println("图片已成功压缩并保存为 " + outputFile.getName());
        } catch (IOException e) {
            System.err.println("图片压缩失败: " + e.getMessage());
        }
    }


    public static BufferedImage compressImage(InputStream inputFileStream, int targetWidth, int targetHeight, boolean rotate, float quality) {
        try {
            // 读取原始图片
            BufferedImage originalImage = ImageIO.read(inputFileStream);

            // 如果需要旋转图片
            if (rotate) {
                originalImage = rotateImage(originalImage);
            }

            // 根据目标宽高压缩图片
            BufferedImage resizedImage = resizeImage(originalImage, targetWidth, targetHeight);

            System.out.println("图片已成功压缩");

            return resizedImage;
        } catch (IOException e) {
            System.err.println("图片压缩失败: " + e.getMessage());
        }
        return null;
    }

    // 根据目标宽高缩放图片
    private static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
        // 创建目标尺寸的图片
        Image resizedImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);

        // 将缩放后的图像转换为BufferedImage
        BufferedImage resizedBufferedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = resizedBufferedImage.createGraphics();
        g2d.drawImage(resizedImage, 0, 0, null);
        g2d.dispose();

        return resizedBufferedImage;
    }

    // 如果需要旋转图片
    private static BufferedImage rotateImage(BufferedImage originalImage) {
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();

        // 创建一个足够大的缓冲图像，适合旋转后的图像
        BufferedImage rotatedImage = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = rotatedImage.createGraphics();

        // 设置透明背景
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 旋转图像90度，图像中心为旋转中心
        g2d.rotate(Math.toRadians(90), height / 2, height / 2);
        g2d.drawImage(originalImage, (height - width) / 2, (width - height) / 2, null);  // 平移以确保图像正确居中
        g2d.dispose();

        return rotatedImage;

    }

    public static void main(String[] args) throws Exception {
        // 示例：压缩图片并旋转90度，压缩质量为0.7，目标宽高为500x500
        File inputFile = new File("D:\\小朋友自画像.png");
        File inputFile_ = new File("D:\\小朋友自画像_.png");

        File outputFile = new File("D:\\小朋友自画像_2.png");
        File outputFil3 = new File("D:\\小朋友自画像_3.png");
        int targetWidth = 1000;
        int targetHeight = 1000;
        boolean rotate = true;
//        boolean rotate = false;
        float quality = 0.7f;

        // compressImage(inputFile, outputFile, targetWidth, targetHeight, rotate, quality);
        // 压缩图片1
        BufferedImage resizedImage1 = compressImage(Files.newInputStream(inputFile.toPath()), targetWidth, targetHeight, rotate, quality);
        // 压缩图片2
        BufferedImage resizedImage2 = compressImage(Files.newInputStream(inputFile_.toPath()), targetWidth, targetHeight, rotate, quality);

        // 合并图片1 和 图片2
        BufferedImage bufferedImageAfterMerged = ImageMergerUtil.mergeImages(resizedImage1, resizedImage2, false);

        // 创建一个 ByteArrayOutputStream 用于将图像数据写入
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 使用 ImageIO 将 BufferedImage 写入 ByteArrayOutputStream
        ImageIO.write(bufferedImageAfterMerged, "JPEG", byteArrayOutputStream);  // 可以根据需要更改图像格式（如 JPG, PNG, 等）
        // 从 ByteArrayOutputStream 获取字节数组，并创建 ByteArrayInputStream
        // 使用你需要的格式，如 PNG 或 JPEG
        // 对压缩
        BufferedImage resizedMergedImage = compressImage(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), targetWidth, targetHeight, false, quality);

        byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(resizedMergedImage, "JPEG", byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        String s = Base64.getEncoder().encodeToString(byteArray);
        System.out.println(s);
    }

}
